const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const jwtConf = require('../config/jwt')

const sql = {
  selectUsername: 'select * from ev_user where username=?',
  insertUser: 'insert into ev_user set ?'
}

//用户注册
exports.reguser = (req, res) => {
  const userinfo = req.body
  try{
    db.query(sql.selectUsername, userinfo.username, (err, results) => {
      if(err) throw err;
      if(results.length > 0 ){
        return res.cc('用户名被占用了，请再想一个更优雅的名称')
      }else{
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        try{
          db.query(sql.insertUser, {
            username: userinfo.username,
            password: userinfo.password,
            email: userinfo.email
          }, (err, results)=>{
            if (err) throw err
            // SQL 语句执行成功，但影响行数不为 1
            if (results.affectedRows !== 1) {
              return res.cc('注册用户失败，请稍后再试！')
            }
            // 注册成功
            res.send({ status: 0, message: '注册成功！' })
          })
        }catch(error){
          console.log(err)
        }
      }
    })
  }catch(error){
    console.log(err)
  }
  
}

//用户登录
exports.login = (req, res) => {
  const userinfo = req.body
  const sqlLogin = `select * from ev_user where username=?`
  db.query(sqlLogin, userinfo.username, (err, results)=>{
    if (err) return res.cc(err)
    if (results.length !== 1) return res.cc('登录失败！')
    //TODO:判断用户输入的登录密码和数据库是否一致
    const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
    if(!compareResult) return res.cc('密码错误，请重新输入！')

    //TODO: 登录成功，生成 token 字符串
    const user = { ...results[0], password: '', user_pic: ''}
    
    //生成 Token 字符串
    const tokenStr = jwt.sign(user, jwtConf.jwtSecretKey, {
      expiresIn: jwtConf.expiresIn //有效期为 10天
    })

    res.send({
      status: 0,
      message: '登录成功！',
      //为了方便客户端使用 token 在服务器端直接拼接上 Bearer 的前缀
      token: 'Bearer '+tokenStr,
    })
  })
}


